var io = require('socket.io')();
var crud = require('../database/crud');
var read = require('../segment/read');

io.on('connection', function (_socket) {
  console.log(' socket 连接创建成功');
  // io.emit('chat message', 'hehe');
  // _socket.on('chat message', function(msg){
  //   console.log('message: ' + msg);
  //
  // });
  read.readText(function(list) {
    var collectionName = 'comment';
    // 初始化数据库连接
    crud.init(collectionName);
    var dataLine = Date.now();
    var wordCount = 0;

    list.map(function(item) {
      wordCount = wordCount + item.segment.length;
    })

    console.log(wordCount);

    var data = {
      dataLine: dataLine,
      data: list,
      wordCount: wordCount
    }

    crud.append(collectionName, data, function() {});
    crud.query(collectionName, {
      dataLine: dataLine
    }, function(result) {
      console.log('查询成功');
      io.emit('chat message', JSON.stringify(result));
    });
  });

  // 读取大单数据
  read.readText(function(list) {
    var collectionName = 'single';

    // 初始化数据库连接
    crud.init(collectionName);
    var dataLine = Date.now();
    var data = {
      dataLine: dataLine,
      data: list
    }

    crud.append(collectionName, data, function() {});
    crud.query(collectionName, {
      dataLine: dataLine
    }, function(result) {
      console.log('查询成功');
      io.emit('chat message', JSON.stringify(result));
    });
  });
});

module.exports = {
  listen: function (_server) {
    return io.listen(_server);
  }
}
